﻿using System;
using System.Reflection;

namespace YioksPlanEditor.ObjectCopy
{
    public class ModelCopy
    {
        /// <summary>
        /// 对象复制，属性一致
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static IModel CopyModel<T>(T t) where T : IModel
        {
            var type = typeof(T);
            //创建类对象                 
            var model = Activator.CreateInstance(type) as IModel;
            //反序列化操作 所定义的变量          
            var oldpropertys = type.GetProperties(BindingFlags.Public | BindingFlags.SetProperty |
                                                   BindingFlags.Instance);
            foreach (PropertyInfo info in oldpropertys)
            {
                var value = info.GetValue(t, null);
                info.SetValue(model, value, null);
            }
            return model;
        }

        /// <summary>
        /// 属性值复制，可实现属性覆盖
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="copyNullValue"></param>
        public static void CopyProperty<T>(T from, T to,bool copyNullValue = true) where T : IModel
        {
            var type = typeof(T);
            //反序列化操作 所定义的变量          
            var oldpropertys = type.GetProperties(BindingFlags.Public | BindingFlags.SetProperty |
                                                   BindingFlags.Instance);
            foreach (var info in oldpropertys)
            {
                var value = info.GetValue(from, null);
                if(!copyNullValue && value == null)continue;
                info.SetValue(to, value, null);
            }
        }
    }
}
